package com.collectplus.express.passport;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.collectplus.express.R;
import com.collectplus.express.app.AppCaptureActivity;
import com.collectplus.express.app.Intents;
import com.collectplus.express.evaluate.EvaluateActivity;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppLogic;
import com.collectplus.express.menu.WebViewActivity;
import com.collectplus.express.model.BoxcodeModel;
import com.collectplus.express.model.PassportDetailBean;
import com.collectplus.express.parcel.ParcelDetailActivity;

import droid.frame.activity.base.BaseViewStub;
import droid.frame.umeng.UMeng;

/**
 * Created by joker on 2018/1/3.
 * passport 只能柜路由的服务评价，查看物流，二维码放，重新获取在这里面操作
 */
public class NewPassportBoxRouteOperate extends BaseViewStub implements View.OnClickListener {

    private PassportDetailBean item;
    /**
     * 操作按钮 ：去评价、查看物流
     */
    private TextView mperateView;
    /**
     * passsport状态为1，开箱剩余时间
     */
    private TextView mRemainView;

    private TextView mCodeText;

    private Context context;

    private View mCodeView;
    CountDownTimer timer = null;

    public NewPassportBoxRouteOperate(Activity context, int resId) {
        super(context, resId);
        this.context = context;
    }

    public void loadLayout(PassportDetailBean item) {
        super.inflate();
        this.item = item;
        mCodeText = (TextView) findViewById(R.id.parcel_code);
        TextView parcelRoute = (TextView) findViewById(R.id.passport_route);
        mperateView = (TextView) findViewById(R.id.parcel_route_operation);
        mRemainView = (TextView) findViewById(R.id.passport_remain_time);
        mperateView.setOnClickListener(this);

        mCodeView = findViewById(R.id.code_operate_item);
        // findViewById(R.id.parcel_scan_img).setOnClickListener(this);

        parcelRoute.setText(item.getStatusDesc());
        if (item.getPassportStatus() == 1) {
            mCodeText.setText(item.getCheckCode());
            // 当状态为1时才设置drawableright,并设置点击
            Drawable drawable = getContext().getResources().getDrawable(R.drawable.arrow_right);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            parcelRoute.setCompoundDrawables(null, null, drawable, null);
            parcelRoute.setOnClickListener(this);

            setCheckCodeStatus();
        } else {
            mCodeView.setVisibility(View.GONE);
            findViewById(R.id.passport_remain_time).setVisibility(View.GONE);
            mperateView.setVisibility(View.VISIBLE);
            mperateView.setText("重新获取");
        }
        handleRouteState();
    }

    public void setNewCode(BoxcodeModel model) {
        item.setCheckCode(model.getCheckCode());
        item.setRemainTime(model.getRemainTime());
        mCodeText.setText(item.getCheckCode());
        setCheckCodeStatus();
    }

    /**
     * 设置开箱码状态
     */
    private void setCheckCodeStatus() {
        mperateView.setVisibility(View.GONE);
        if (item.getRemainTime() > 0) {
            mCodeView.setVisibility(View.VISIBLE);
            remaintimeCountdown(mRemainView, item.getRemainTime());
            // 倒计时定时器
            timer = new CountDownTimer(item.getRemainTime(), 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    remaintimeCountdown(mRemainView, millisUntilFinished);
                }

                @Override
                public void onFinish() {
                }
            };
            timer.start();
        } else {
            remaintimeCountdown(mRemainView, 0);
            mperateView.setVisibility(View.VISIBLE);
            mCodeView.setVisibility(View.GONE);
        }
    }

    private void remaintimeCountdown(TextView countDown, long remainTime) {
        String[] diffs = AppLogic.getInstance().timeDiffStr(remainTime);
        String timeText = "";
        if (diffs.length == 0) {
            timeText = "快递柜保留时间剩余：00:00:00";
        } else if (diffs.length == 1) {
            timeText = "快递柜保留时间剩余：00:00:" + diffs[0];
        } else if (diffs.length == 2) {
            timeText = "快递柜保留时间剩余：00:" + diffs[0] + ":" + diffs[1];
        } else if (diffs.length == 3) {
            timeText = "快递柜保留时间剩余：" + diffs[0] + ":" + diffs[1] + ":" + diffs[2];
        }
        int sencondStart = timeText.indexOf("：");
        SpannableString secondSp = new SpannableString(timeText);
        secondSp.setSpan(new TextAppearanceSpan(getContext(), R.style.passort_count_down_style), sencondStart + 1, timeText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        countDown.setText(secondSp, TextView.BufferType.SPANNABLE);
        // countDown.setText(timeText);
        if (remainTime <= 0) {
            countDown.setText("寄件码已过期，请重新获取！");
            mperateView.setVisibility(View.VISIBLE);
            mperateView.setText("重新获取");
            mCodeView.setVisibility(View.GONE);
        }
    }

    /**
     * 处理路由
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void handleRouteState() {
        // 状态文本
        TextView statusText = (TextView) findViewById(R.id.passport_state);
        // 状态点击事件
        statusText.setOnClickListener(this);
        //驿站投递包裹指南，只在待投递显示
        ImageView parcelHelperIV = (ImageView) findViewById(R.id.parcelhelp_IV);
        parcelHelperIV.setOnClickListener(this);
        TextView routeInformation = (TextView) findViewById(R.id.passport_route);
        parcelHelperIV.setVisibility(View.GONE);
        if (item.getIsBox()) {
            routeInformation.setText(item.getStatusDesc());
            if (item.getPassportStatus() == 1) {
                setParcelProgressBar(1, 0, 0, 0, 0);
                statusText.setText("待投递");
                parcelHelperIV.setVisibility(View.VISIBLE);
            } else if (item.getPassportStatus() == 2) {
                setParcelProgressBar(1, 1, 0, 0, 0);
                statusText.setText("待揽收");
                //                if (isNotEmpty(item.getPickOutTime())) {
                //                    routeOuttimeMessagemation.setText(item.getPickOutTime());
                //                    routeOuttimeMessagemation.setVisibility(View.VISIBLE);
                //                } else {
                //                    routeOuttimeMessagemation.setVisibility(View.INVISIBLE);
                //                }
            } else if (item.getPassportStatus() == 3) {
                setParcelProgressBar(1, 1, 1, 0, 0);
                statusText.setText("待交接");
            } else if (item.getPassportStatus() == 4) {
                setParcelProgressBar(1, 1, 1, 1, 0);
                statusText.setText("待送达");
                mperateView.setText("查看物流");
            } else if (item.getPassportStatus() == 5) {
                setParcelProgressBar(1, 1, 1, 1, 1);
                statusText.setText("待评价");
                mperateView.setText("去评价");
            }
        }
    }

    /**
     * 物流状态条颜色
     *
     * @param colors 1.到柜；2驿站
     */
    @SuppressWarnings("deprecation")
    private void setParcelProgressBar(int... colors) {
        ImageView item1 = (ImageView) findViewById(R.id.passport_progress_1);
        ImageView item2 = (ImageView) findViewById(R.id.passport_progress_2);
        ImageView item3 = (ImageView) findViewById(R.id.passport_progress_3);
        ImageView item4 = (ImageView) findViewById(R.id.passport_progress_4);
        ImageView item5 = (ImageView) findViewById(R.id.passport_progress_5);

        GradientShape shape1 = new GradientShape(getContext());
        GradientShape shape2 = new GradientShape(getContext());
        GradientShape shape3 = new GradientShape(getContext());
        GradientShape shape4 = new GradientShape(getContext());
        GradientShape shape5 = new GradientShape(getContext());

        shape1.setStyle(0, colors[0]);
        shape2.setStyle(1, colors[1]);
        shape3.setStyle(1, colors[2]);
        shape4.setStyle(1, colors[3]);
        shape5.setStyle(2, colors[4]);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            item1.setBackground(shape1);
            item2.setBackground(shape2);
            item3.setBackground(shape3);
            item4.setBackground(shape4);
            item5.setBackground(shape5);
        } else {
            item1.setBackgroundDrawable(shape1);
            item2.setBackgroundDrawable(shape2);
            item3.setBackgroundDrawable(shape3);
            item4.setBackgroundDrawable(shape4);
            item5.setBackgroundDrawable(shape5);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.passport_route:
                UMeng.click(getContext(), "passport_how2useBox_click");
                Intent webIntent = new Intent();
                webIntent.setClass(getContext(), WebViewActivity.class);
                webIntent.putExtra("title", "如何使用快递柜");
                getContext().startActivity(webIntent);
                break;
            case R.id.parcel_scan_img:
                Intent captureIntent = new Intent();
                captureIntent.setClass(getContext(), AppCaptureActivity.class);
                captureIntent.setAction(Intents.capture_station);
                getContext().startActivity(captureIntent);
                break;
            case R.id.parcel_route_operation:
                // 查看物流
                if (item.getPassportStatus() == 4) {
                    Intent intent = new Intent(getContext(), ParcelDetailActivity.class);
                    intent.putExtra("parcelStatus", item.getParcelStatus());
                    intent.putExtra("parcelId", item.getParcelId());
                    intent.putExtra("from", 1);
                    getContext().startActivity(intent);
                    // 服务评论
                } else if (item.getPassportStatus() == 5) {
                    Intent intent = new Intent(getContext(), EvaluateActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("orderId", item.getOrderId());
                    intent.putExtras(bundle);
                    getContext().startActivityForResult(intent, 1001);
                } else if (item.getPassportStatus() == 1) {
                    AppHttp.getInstance().getBoxCode(item.getParcelId());
                }
                break;
            case R.id.parcelhelp_IV:
                UMeng.click(getContext(), "passport_how2useBox_click");
                Intent webHelperIntent = new Intent();
                webHelperIntent.setClass(getContext(), WebViewActivity.class);
                webHelperIntent.putExtra("title", "如何使用快递柜");
                getContext().startActivity(webHelperIntent);
                break;
            default:
                break;
        }
    }

    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}
